import { useEffect, useState } from 'react'
import { Image, Ellipsis, NavBar, Skeleton, Button, Popover, Dialog, Toast } from 'antd-mobile'
import styles from "./index.module.less"
import HeaderNav from "@/components/header-nav"
import FooterNav from "@/components/footer-nav"

import { useSearchParams, useParams } from 'react-router-dom'
import { DeleteOutline, EditSOutline, EyeOutline, MoreOutline } from 'antd-mobile-icons'
import { param } from 'jquery'
const { getUserWorldBookDetails, getWorldBookRoleChatList, createChat,deleteRole } = $globalServicer('world')
const ItemCrad = (props) => {
  const customNavigate = $globalNavigate()
  const [params] = useSearchParams();
  console.log("🚀 ~ ItemCrad ~ params:", params)
  const id = params.get('id');
  console.log(`------id`, id)
  const type = params.get('type');
  console.log(`------type`, type)
  const [worldInfo, setWorldInfo] = useState(null)
  useEffect(() => {
    if (id) {
      getUserWorldBookDetails(id).then(res => {
        console.log(`------res`, res)
        setWorldInfo(res)
      });
    }
    getWorldBookRoleChatList().then(res => {
      console.log(`------result`, res)
    });
  }, [])
  const handleOperate = (node, item) => {
    console.log('handleOperate', node)
    console.log('handleOperate', item)
    if (node.key === 'delete') {
      Dialog.confirm({
        content: '是否确认删除该角色？',
        cancelText:
          <div className={styles.cancelClass}>
            取消
          </div>,
        confirmText: <div className={styles.confirmClass}>确认</div>,
        onConfirm: async () => {
          await deleteRole({ id: item.id }).then(res => {
            Toast.show({
              content: '删除成功',
              icon: 'success',
            });
            customNavigate('/world')
          })
        },
      })
    } else if (node.key === 'edit') {
      console.log('edit', worldInfo)
      if (worldInfo.type === 1) {
        customNavigate(`/world/createRoleAndWorld?id=${id}&roleId=${item.id}&type=edit`)
      } else {
        customNavigate(`/world/createMixRoleWorld?id=${id}&roleId=${item.id}&type=edit`)
      }
    }
  }
  const sendMessage = async (id) => {
    window.selectCharacterById(id);
    const Elements = document.getElementsByClassName('no-blur')
    console.log("🚀 ~ sendMessage ~ Elements:", Elements)
    Elements[1].style.display = 'block';
    console.log(`-----发送事件`);
    await window.eventSource.emit('chat_id_changed', 'AA - 2024-9-1 @03h 34m 57s 372ms');
    const textArea = document.getElementById('send_textarea');
    console.log("🚀 ~ sendMessage ~ document:", document)
    console.log("🚀 ~ sendMessage ~ textArea:", textArea)
    // textArea.value = '22222';
    // const send_but = document.getElementById('send_but');
    // send_but.click();
  }
  const handleTagClick = (item) => {
    console.log('handleTagClick')
    console.log('item', item)
    let st_chat_id = item.st_chat_id || ''
    let name = item.name || ''
    let user_world_id = item.user_world_id || ''
    if (item.chat_group_id === 0) {
      const data = {
        type: 1, // 1 角色聊天 2 世界聊天
        roles: [
          item.id
        ]
      }
      createChat(data).then(res => {
        customNavigate('/chatlist')
        // customNavigate(`/chatDetail?type=1&chatId=${res.chat_id}&name=${name}&userWorldId=${user_world_id}`)
      })
    } else {
      customNavigate('/chatlist')
      // TODO: 这里直接调用角色的 st_chat_id
      // customNavigate(`/chatDetail?type=1&chatId=${st_chat_id}&name=${name}&userWorldId=${user_world_id}`)
    }
  }
  const backWorldBookDetail = () => {
    const Elements = document.getElementsByClassName('no-blur')
    console.log("🚀 ~ sendMessage ~ Elements:", Elements)
    if (Elements.length) {
      if (Elements[1].style.display === 'none') {
        customNavigate(-1)
      } else {
        Elements[1].style.display = 'none';
      }
    } else {
      customNavigate(-1)
    }
  }
  const actions = [
    {
      key: 'edit',
      text: '编辑',
      path: 'createRoleAndWorld',
    },
    {
      key: 'delete',
      text: '删除',
      path: 'createRoleWorld1',
    },
  ]
  return (
    <>
      <div className={styles.detail_warp}>
        <div className={styles.headerTop}
          // style={{ backgroundImage: `url(${worldInfo?.world_cover})`, backgroundSize: 'cover' }}
          style={{ backgroundImage: `url(${worldInfo?.world_cover})`, backgroundSize: 'cover' }}
        >

          <div className={styles.mask}>
            <div className="header">
              <HeaderNav backArrow={true}
                onBack={backWorldBookDetail}
                title={worldInfo?.world_name}
                styleObj={{ color: '#fff' }}
              >
              </HeaderNav>
            </div>
            <div className={styles.desc}>
              {
                worldInfo?.world_description
              }
            </div>
          </div>
        </div>
        <div className={styles.descWrapper}>
          <div className={styles.classifyListWrapper}>
            <p className={styles.classifyTitle}>
              主要角色介绍
            </p>
            <div className={styles.personList}>
              {
                worldInfo?.roles?.map((item, index) =>
                  <div className={styles.roleItem} key={item.id}>
                    <div className={styles.itemTop}>
                      <div className={styles.itemLeft}>
                        <img src={item.cover} alt="" />
                        <span className={styles.itemName}>{item.name}</span>
                      </div>
                      <div className={styles.itemRight}>
                        <span className={styles.more}>
                          <Popover.Menu
                            actions={actions}
                            placement='bottom-start'
                            onAction={node => handleOperate(node, item)}
                            trigger='click'
                          >
                            <MoreOutline color='#898989' />
                          </Popover.Menu>
                        </span>
                        <Button
                          shape="rounded"
                          fill="outline"
                          className={`${styles.tag} ${styles.selected}`}
                          onClick={() => handleTagClick(item)}
                        >
                          聊天
                        </Button>
                      </div>
                    </div>
                  </div>
                )
              }
            </div>
          </div>
        </div>

      </div>
      <div className="footer">
        <FooterNav></FooterNav>
      </div>
    </>

  );
};

export default ItemCrad;
